//
//  SBMenuController.m
//  MailNotify
//
//  Created by Luke van der Hoeven on 5/14/08.
//  Copyright 2008 Cedarville University. All rights reserved.
//

#import "SBMenuController.h"

@implementation SBMenuController

- (void)awakeFromNib {
	NSTimer *timer;
	mail = [SBApplication applicationWithBundleIdentifier:@"com.apple.mail"];
	
	unreadMessages = [[MailArray alloc] init];
	
	NSStatusBar *bar = [NSStatusBar systemStatusBar];
	
    sbStatus = [bar statusItemWithLength:NSVariableStatusItemLength];
    [sbStatus retain];
	
	NSString *path = [[NSBundle mainBundle] pathForResource:@"Picasso 2" ofType:@"icns"]; 
	NSImage *image = [[NSImage alloc] initWithContentsOfFile: path];
	
	NSSize size = NSMakeSize(16.0, 16.0);
	[image setSize:size];
	
	[self updateMailItems:self];
	
	[sbStatus setImage:image];
    [sbStatus setHighlightMode:YES];
    [sbStatus setMenu:sbMenu];
	
	if (self) {
		timer = [NSTimer scheduledTimerWithTimeInterval:60
												 target:self 
											   selector:@selector(updateMailItems:) 
											   userInfo:nil 
												repeats:YES];
	}
}

//does the main updating of the menu (how many unread and titles in dropdown)
- (void)updateMailItems:(id)sender {
	//set the status to number of unread
	NSString *temp = [NSString stringWithFormat:@"%d", [[mail inbox] unreadCount]];
	[sbStatus setTitle:temp];
	
	int i;
	for(i=3; i<[sbMenu numberOfItems]; i++) {			
		NSLog(@"Removing from menu: %@", [[sbMenu itemAtIndex:i] title]);
		[sbMenu removeItemAtIndex:i];
		i--;
	}
	
	NSArray *messages = [[[mail inbox] messages] get];
	for(MailMessage *msg in messages) {
		if(![msg readStatus]) {
			NSString *t = [NSString stringWithFormat:@"%d - %@", [msg id], [msg subject]];
			[sbMenu addItemWithTitle:t action:nil keyEquivalent:@""];
			NSLog(@"Adding to menu: %@", t);
			
			if(![unreadMessages isAdded:[msg id]]) {
				NSLog(@"Being added to unread: %@", t);
				[unreadMessages add:[msg id] obj:msg];
			} 
		} else if([unreadMessages isAdded:[msg id]]) {
			[unreadMessages remove:[msg id]];
		}
	}	
}

- (void)openMessage:(id)sender {

}

- (IBAction)openMail:(id)sender {
	[mail activate];
	[mail release];
}



@end
